package com.ruben.study;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * ThreadLocal例子
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/10/23 16:43
 */
public class ThreadLocalDemo {

    private static final ThreadLocal<Long> MY_LONG_THREAD = new ThreadLocal<>();
    private static final ThreadLocal<Long> MY_LONG_INHERITABLE_THREAD = new InheritableThreadLocal<>();

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MY_LONG_THREAD.set(0L);
        MY_LONG_INHERITABLE_THREAD.set(1L);
        // 单线程共享变量
        CompletableFuture.runAsync(() -> {
            // 子线程尝试访问ThreadLocal中的值
            System.out.println(MY_LONG_THREAD.get());
            System.out.println(MY_LONG_INHERITABLE_THREAD.get());
        }).get();
        MY_LONG_THREAD.remove();
        MY_LONG_INHERITABLE_THREAD.remove();
    }
}
